package com.haoniu.web.controller.system;

import com.haoniu.common.base.AjaxResult;
import com.haoniu.common.constant.ShiroConstants;

import com.haoniu.common.utils.IpUtils;
import com.haoniu.common.utils.Md5Utils;
import com.haoniu.common.utils.StringUtils;
import com.haoniu.framework.util.ServletUtils;
import com.haoniu.framework.web.service.RedisService;
import com.haoniu.web.core.base.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证
 *
 * @author haoniu
 */
@Controller
public class SysLoginController extends BaseController {

    @Autowired
    private RedisService redisService;

    @Value("${sms.captchaEnabled}")
    private boolean captchaEnabled;

    @Value("${sms.key}")
    private String key;

    private static String msgSign = "msgSign";

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        boolean captchaEnable = captchaEnabled;
        if(captchaEnable){
            // 获取cookie,判断是否需要短信验证码验证
            Cookie[] cookies =  request.getCookies();
            if(cookies != null){
                String cookieSign = null;
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals(msgSign)){
                        cookieSign = cookie.getValue();
                    }
                }
                if(StringUtils.isNotBlank(cookieSign)){
                    String sign = redisService.getConfig(msgSign);
                    if(cookieSign.equals(sign)){
                        captchaEnable=false;
                    }
                }
            }
        }
        modelMap.addAttribute("captchaEnabled",captchaEnable);
        String ip = IpUtils.getIpAddr(request);
        redisService.setConfig(ip+":captchaEnabled",captchaEnable);
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, String authCode, Boolean rememberMe) {
        ServletUtils.getRequest().setAttribute(ShiroConstants.AUTHCODE, authCode);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);

            HttpServletRequest request = ServletUtils.getRequest();
            String ip = IpUtils.getIpAddr(request);
            String signSrc = "ip="+ip+"username=" + username + "|" + "password=" + password + "key=" + key;
            String sign = Md5Utils.hash(signSrc);
            Cookie cookie = new Cookie(msgSign, sign);
            cookie.setMaxAge(7*60*60);
            ServletUtils.getResponse().addCookie(cookie);
            redisService.setConfig(msgSign,sign);

            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "/error/unauth";
    }
}
